package fun.formoji.commons.util;

/**
 * @author Sukit
 * 卡号/手机号/openId卡号加密
 */
public class EncryptUtils {

    public static String encryptCardNo(String cardNo) {
        if (cardNo == null || "".equals(cardNo) || "-".equals(cardNo) || "--".equals(cardNo) || "99999999999".equals(cardNo)) {
            return null;
        }
        cardNo = cardNo.replaceAll("[ ]", "");
        return encrypt(cardNo);
    }

    public static String encryptMobileNo(String mobileNo) {
        if (mobileNo == null || "".equals(mobileNo) || "-".equals(mobileNo) || "--".equals(mobileNo)) {
            return null;
        }
        return encrypt(mobileNo);
    }

    public static String encryptOpenId(String openId) {
        if (openId == null || "".equals(openId) || "-".equals(openId) || "--".equals(openId)) {
            return null;
        }
        return "w" + openId;
    }

    private static String encrypt(String number) {
        int len = number.length();
        if (len < 11) {
            //会员卡卡号11位
            return null;
        }
        Integer res = (Integer.parseInt(number.charAt(len - 4) + "") + Integer.parseInt(number.charAt(len - 3) +
                "") * 2 + Integer.parseInt(number.charAt(len - 2) + "") * 3 + Integer.parseInt(number.charAt(len - 1) + "") * 4);
        String resStr = "";
        if (res < 10) {
            //只有一位的后面补一个0，补全2位。
            resStr = res.toString() + '0';
        } else {
            resStr = res.toString();
        }
        return number.substring(0, 3) + resStr.charAt(resStr.length() - 2) + resStr.charAt(resStr.length() - 1) + number.substring(3);
    }

}
